<template>
    <div class="index-page">
        <div class="index-header forbid-select">
            <div class="index-title animate__animated animate__zoomIn" style="color: white">
                <div @click="go" class="cursor-pointer">
                    {{ getWebInfo.websiteName }}
                </div>
            </div>
            <div class="flex-display-center animate__animated animate__fadeInLeft">
                <div class="typewriter">
                    <div class="typing">曾梦想仗剑走天涯, 看一看世界的繁华</div>
                </div>
            </div>
        </div>

        <icon :class="`weather-icon-${currentWeather.icon} weather animate__animated animate__fadeInLeft`"
            @dblclick="getWeather(true)" @click="showWeatherInfo = !showWeatherInfo" />

        <weatherCharts v-model="showWeatherInfo" />

        <base-footer v-if="mobile" />
    </div>
</template>

<script setup>
import { useMainStore } from "@/pinia"
import router from "@/router"
import { useParallax, useEventListener } from '@vueuse/core'
import { storeToRefs } from "pinia"
import { mobile } from "@/utils/tools"
import { jsonp } from "@/utils/tools"
import { apiPrefix } from "@/utils/constant"
import { useRequest } from "@usehook"
import weatherCharts from "@/components/weather/weatherCharts"

const mainStore = useMainStore()
let timeout = $ref(null)
let currentWeather = $ref("")

const go = () => {
    if (!mobile) router.push("/note")
}

const { getWebInfo } = storeToRefs(mainStore)

const darkDocument = document.querySelector('.dark-background')
const parallax = reactive(useParallax(document.querySelector('.dark-background')))

watch(() => parallax, (value) => {
    darkDocument.style.transform = `translateX(${value.tilt * 20}px) translateY(${value.roll * 20
        }px) scale(1.05)`
}, { deep: true })

useEventListener('resize', () => {
    clearTimeout(timeout)
    darkDocument.style.transition = ""
    timeout = setTimeout(() => {
        darkDocument.style.transition = '.3s ease-out all'
    }, 500)
})

const getLocationInfo = () => {
    let url = "https://apis.map.qq.com/ws/location/v1/ip"
    return jsonp(url, {
        key: "DCUBZ-FBWRZ-XIIXU-TGCMF-XCJJE-VGB22",
        output: 'jsonp'
    })
}
let location = $ref({ ad_info: { province: "", city: "", district: "" } })
const locationKey = "location"
let miWeatherMap = $ref({})
let showWeatherInfo = $ref(false)

const getLocation = () => {
    return JSON.parse(sessionStorage.getItem(locationKey) || "{}")
}

const setLocation = (location) => {
    return sessionStorage.setItem(locationKey, JSON.stringify(location))
}

let weather = $ref({
    temperature: { unit: "℃", value: "0" },
    feelsLike: { unit: "℃", value: "0" },
    humidity: { unit: "%", value: "10" },
    pressure: { unit: "hPa", value: "100" },
    day: { from: 0, to: 0 }
})
const getWeather = async (refresh) => {
    if (refresh || !weather.updateTime || new Date().getTime() - weather.updateTime > 300000) {
        let newLocation = getLocation()
        if (refresh || !newLocation || Object.keys(newLocation).length === 0) {
            const locationResp = await getLocationInfo()
            setLocation(locationResp.result)
            newLocation = locationResp.result
        }
        location = newLocation
        useRequest({
            url: apiPrefix + '/weather',
            latitude: location.location.lat, longitude: location.location.lng
        }).then(resp => {
            if (resp && resp.status) {
                const mapData = resp.data.dict
                mainStore.setWeatherData(resp.data)
                for (let dict of Object.keys(mapData)) {
                    const splitData = mapData[dict].split("@")
                    mapData[dict] = { name: splitData[1], icon: splitData[0] }
                }
                miWeatherMap = mapData
                weather = resp.data.current
                weather.updateTime = resp.data.updateTime
                weather.day = resp.data.forecastDaily.weather.value[0]
                currentWeather = miWeatherMap[weather.weather]
            }
        })
    }
}

onMounted(() => {
    darkDocument.style.transition = '.3s ease-out all'
    darkDocument.style.transform = `scale(1.05)`
    getWeather()
    document.querySelector(".inner-main").style.backdropFilter = "none"
})

onUnmounted(() => {
    setTimeout(() => {
        darkDocument.style.transition = ''
    }, 500)

    darkDocument.style.transform = 'scale(1)'
    document.querySelector(".inner-main").style.backdropFilter = ""
})
</script>

<style scoped>
.index-header {
    position: absolute;
    top: 25vh;
    width: calc(100vw - 20px);
    font-family: fojiya, cursive, monospace;
    font-weight: bold;
    pointer-events: all;
}

:deep(.index-title) {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-bottom: 30px;
    font-size: 60px;
}


:deep(.typewriter) {
    margin: 15px auto 0 auto;
}

/* CSS样式 */
:deep(.typewriter) {
    width: fit-content;
    text-align: center;
    padding: 0 10px;
    margin: auto;
    background: rgba(0, 0, 0, .3);
    border-radius: var(--border-radius);
}

:deep(.typewriter .typing) {
    color: #ffffff;
    overflow: hidden;
    border-right: .15em solid orange;
    white-space: nowrap;
    margin: 10px auto;
    letter-spacing: .15em;
    animation: typing 10s steps(30, end) infinite forwards, blink-caret 1.2s step-end infinite forwards;
}

:deep(.weather) {
    position: absolute;
    top: 0;
    left: 5px;
    pointer-events: all;
}

@keyframes typing {
    0% {
        width: 0
    }

    35%,
    55% {
        width: 21em;
    }

    85%,
    100% {
        width: 0;
    }
}

@keyframes blink-caret {

    from,
    to {
        border-color: transparent
    }

    50% {
        border-color: orange
    }
}

.index-page {
    width: 100%;
    height: 100%;
    position: absolute;
    pointer-events: none;
    top: 0;
    left: 0;
}

.mobile .index-page {
    position: relative;
}

.mobile .index-header {
    width: 100%;
}

:deep(.weather-info) {
    position: absolute;
    top: 50px;
    left: 5px;
    width: fit-content;
    background: rgba(0, 0, 0, .2);
    backdrop-filter: blur(5px);
    padding: 10px;
    box-shadow: -1px 1px 5px rgb(98 98 98 / 20%) inset;
    font-size: 16px;
    border-radius: var(--border-radius);
    pointer-events: all;
}

:deep(.info-label) {
    color: antiquewhite;
}

:deep(.info-value) {
    color: antiquewhite;
    padding-left: 5px;
}

:deep(.info-item) {
    display: flex;
    align-items: center;
}

:deep(.info-item+.info-item) {
    padding-top: 10px;
}

.mobile .weather-info {
    font-size: var(--font-size);
    background: rgb(147 147 147 / .8);
    backdrop-filter: none;
}
</style>

<style>
html:has(.index-page) .user-avatar {
    transform: translateX(0);
    transition: transform 0.5s;
}

html:has(.index-page) .setting {
    transform: translateX(0);
    transition: transform 0.5s;
}
</style>